package com.rtx.wms.std.qm.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.qimen.api.QimenClient;
import com.qimen.api.QimenRequest;
import com.qimen.api.request.EntryorderConfirmRequest;
import com.qimen.api.request.EntryorderConfirmRequest.EntryOrder;
import com.qimen.api.request.EntryorderConfirmRequest.OrderLine;
import com.qimen.api.response.EntryorderConfirmResponse;
import com.rtx.wms.std.asn.bean.ApiReceiptdetailfinish;
import com.rtx.wms.std.asn.bean.ApiReceiptfinish;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.log.bean.WmsLogBo;
import com.rtx.wms.std.log.service.impl.EntryorderConfirmLog;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.XmlWriter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;

/**
 * 收货单回传
 */
@Service
public class EntryorderConfirmService extends QimenService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	EntryorderConfirmLog entryorderConfirmLog;
	

	
	public void entryorderConfirm(String wmwhseid,ApiReceiptfinish apiReceiptfinish) {
		QimenClient client = getQimenClient();
		//测试
		if(Arrays.asList("C1689650364732,C1688969618777".split(",")).contains(apiReceiptfinish.getQmcustomerid())) {
			client = getTestQimenClient();
		}
		if(apiReceiptfinish.getQmcustomerid().startsWith("C")) {
			client = getTestQimenClient();
		}

		WmsLogBo logBo = new WmsLogBo();
		try {

			String uuid = UUID.randomUUID().toString();
			EntryorderConfirmRequest req =	mappingTorequest(apiReceiptfinish);
			
			handle2366(req,apiReceiptfinish);
			
	        logBo.setOriginalData(apiReceiptfinish);
	        logBo.setApiRequest(req);
			
			XmlWriter writer = new XmlWriter(true, "request", QimenRequest.class);
			String requestStr = writer.write(req);
			logger.info("uuid{}-externreceiptkey-{}-entryOrder回传数据:{}",uuid,apiReceiptfinish.getExternreceiptkey(),requestStr);
			EntryorderConfirmResponse rsp  = client.execute(req);
			logBo.setApiResponse(rsp);
			logger.info("uuid-{}-externreceiptkey-{}-entryOrder回传数据结果:{}",uuid,apiReceiptfinish.getExternreceiptkey(),JSON.toJSONString(rsp));
			if(rsp.isSuccess()){
				apiReceiptfinish.setEdiflag(WmsConstant.SUCCESS_FLAG);
			}else{
				apiReceiptfinish.setEdiflag(WmsConstant.FAIL_FLAG);
				apiReceiptfinish.setEdimsg(rsp.getMessage());
			}
		} catch (ApiException e) {
			logger.error("入库单：{}回传奇门异常",apiReceiptfinish.getReceiptkey(),e);
			apiReceiptfinish.setEdiflag(WmsConstant.FAIL_FLAG);
			apiReceiptfinish.setEdimsg(e.getMessage());
			logBo.setMsg(e.getMessage());
		}

		try {
			entryorderConfirmLog.recordLog(wmwhseid, logBo);
		} catch (Exception e) {
			logger.error("记录日志异常",e);
		}
	}
	
	
	private EntryorderConfirmRequest mappingTorequest(ApiReceiptfinish wmsData) {
		EntryorderConfirmRequest req = new EntryorderConfirmRequest();
		req.setCustomerId(wmsData.getQmcustomerid());
		req.setVersion("2.0");
		EntryOrder entryOrder = new EntryOrder();
		entryOrder.setTotalOrderLines(Long.valueOf(wmsData.getDetails().size()));
		entryOrder.setEntryOrderType(wmsData.getRtxqmtype());
		entryOrder.setConfirmType(1l);
		entryOrder.setEntryOrderCode(wmsData.getExternreceiptkey());
		entryOrder.setOwnerCode(wmsData.getRtxshipstoreConfig().getCode());
		entryOrder.setWarehouseCode(wmsData.getWhseid().toLowerCase());
		entryOrder.setEntryOrderId(wmsData.getReceiptkey());
		entryOrder.setOutBizCode(wmsData.getBatchid());
		try {
			entryOrder.setOperateTime(DateUtil.format(wmsData.getReceiptdate(), "yyyy-MM-dd HH:mm:ss"));
		} catch (Exception e) {
			logger.error("时间转换异常",e);
		}
		entryOrder.setRemark(wmsData.getNotes());
		entryOrder.setFreight("0");
		req.setEntryOrder(entryOrder);

		Double totalQtyreceived = 0.0;
		Double totalQtyexpected = 0.0;
		List<OrderLine> orderlines = new ArrayList<OrderLine>();
		for(ApiReceiptdetailfinish detail:wmsData.getDetails()) {
			OrderLine orderLine = new OrderLine();
			orderLine.setOwnerCode(wmsData.getRtxshipstoreConfig().getCode());
			orderLine.setItemCode(detail.getSku());
			Double qtyreceived =Double.parseDouble(detail.getQtyreceived()) ;
			orderLine.setActualQty(qtyreceived.longValue());


			orderLine.setInventoryType("ZP");
			orderlines.add(orderLine);
		}

//		if(totalQtyreceived<totalQtyexpected) {
//			entryOrder.setStatus("PARTFULFILLED");
//		}else if(totalQtyreceived==totalQtyexpected){
			entryOrder.setStatus("FULFILLED");
			entryOrder.setConfirmType(0l);
//		}else {
//			entryOrder.setStatus("EXCEPTION");
//		}

		req.setOrderLines(orderlines);
		return req;
	}
	
	
	 /**
	     * 兆君回传逻辑
	* @param req
	* @param apiOrdersfinish
	*/
	void handle2366(EntryorderConfirmRequest req,ApiReceiptfinish r){
		if("2366".equals(r.getStorerkey())) {
			req.getEntryOrder().setWarehouseCode(r.getRtxpofromhourse());
			req.getEntryOrder().setOwnerCode(r.getDefault01());
		}
	}
}
